<template>
  <a-modal width="760px" :visible="visible" :title="TITLE[showType]" @cancel="handleCancel">
    <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="directoryRef">
      <template #memberIds="{ question }">
        <a-select allow-clear :options="localState.memberIdsOptions" placeholder="请选择" mode="multiple" v-model:value="question.memberIds"></a-select>
      </template>
    </DynamicForm>

    <template #footer>
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" :loading="state.loading" @click="handleOk">{{ OK_TEXT[showType] }}</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { DynamicForm } from '@/components/public-template';
import { Api, deptSave, listByOrgId } from '@/config/api/deptFile';
import { RESETTABLE } from '@/mixins/subject/subject-types';
import { message } from 'ant-design-vue';
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import viewService from './viewDialog.service';

const props = defineProps({
  visible: { type: Boolean, default: false },
  data: { type: Object },
  showType: { type: String, default: 'ADD' },
  parentId: { type: String },
  detailId: { type: String }
});
const emit = defineEmits(['update:visible', 'handleEdit']);
const { proxy }: any = getCurrentInstance();

const state = reactive({
  loading: false,
  memberIdsValue: [],
  id: '' // 本地当前用户id
});

const TITLE = {
  ADD: '添加文件夹',
  VIEW: '文件夹详情',
  EDIT: '编辑文件夹'
};
const OK_TEXT = {
  ADD: '确定',
  VIEW: '编辑',
  EDIT: '确定'
};
const localState = {
  memberIdsOptions: []
};
state.id = JSON.parse(window.localStorage.getItem('LOGIN__INFO__'))['id'];
const directoryRef = ref(null);
const dyQuestions: any = reactive(props.showType === 'VIEW' ? viewService.getViewQuestions() : viewService.getQuestions(state.id, props.showType));
const dyConfig: any = {
  queryUrl: props.showType !== 'ADD' ? Api.deptGet : '',
  urlName: props.detailId,
  noGetDataParams: props.showType !== 'ADD' ? true : false,
  grid: 12,
  labelCol: 12,
  layout: 'vertical',
  cancelSave: true,
  beforeWithMethod: (from) => {
    const data = JSON.parse(JSON.stringify(from));

    if (props.showType === 'VIEW') {
      dyQuestions[4].value = data.deptFilePermissionResps.map((item) => {
        return { permission: Number(item.permission), memberNames: item.memberNames };
      });
    } else if (props.showType === 'EDIT') {
      dyQuestions[4].value = data.deptFilePermissionResps.map((item) => {
        return { permission: Number(item.permission), memberIds: item.memberIds.split(',') };
      });
    }

    return data;
  }
};

onMounted(() => {
  getListByOrgId();
});

const getListByOrgId = () => {
  listByOrgId({ id: JSON.parse(window.localStorage.getItem('LOGIN__INFO__'))['orgId'] }).then((res) => {
    if (res && res.success) {
      localState.memberIdsOptions = res.data.map((item) => {
        return { label: item.nickName, value: item.id, key: item.id };
      });
    }
  });
};

function handleOk() {
  if (props.showType == 'VIEW') {
    emit('handleEdit', props.data);
  } else {
    directoryRef.value.onFinish(({ code, name, watermarkingId, customTable }) => {
      state.loading = true;
      let params = { code, name, watermarkingId, deptFilePermissionDTOS: customTable, parentId: props.parentId, id: props.detailId !== '' ? props.detailId : '' };

      // 用户多选，逗号分隔
      for (let i of params.deptFilePermissionDTOS) {
        i.memberIds = i.memberIds.join(',');
      }

      deptSave(params)
        .then((result) => {
          if (result.success) {
            message.success(`${props.showType == 'ADD' ? '添加' : '修改'}成功`);
            proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'deptFile' } });
            emit('update:visible', false);
          }
          state.loading = false;
        })
        .catch((err) => {
          state.loading = false;
          return Promise.reject(err);
        });
    });
  }
}

const handleCancel = () => {
  emit('update:visible', false);
};
</script>

<style lang="less" scoped>
:deep(.ant-table-cell .ant-row.ant-form-item) {
  margin-bottom: 0;
}
</style>
